package com.ziyun.pop.mall.module.order.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.service.common.constant.AppType;
import com.service.common.protocol.ResultCode;
import com.service.order.api.OrderService;
import com.service.order.api.PayService;
import com.service.order.constant.OrderResult;
import com.service.order.constant.PayChannelType;
import com.service.order.constant.PayType;
import com.service.order.dao.OrderInfoDao;
import com.service.order.exception.OrderException;
import com.service.order.model.order.PayOrderResultDto;
import com.service.order.model.pay.OrderPayInfoResultDto;
import com.service.order.model.pay.PayParamDto;
import com.service.utils.push.umeng.JsonResult;
import com.utility.StringUtils;
import com.ziyun.pop.mall.module.order.config.OrderConfig;
import com.ziyun.pop.mall.system.config.HttpRequestLocal;


/**
 * OrderPay 接口
 */
/**
 * @author PC
 *
 */
/**
 * @author PC
 *
 */
@Controller
public class MallOrderPayController {

	private final Log log = LogFactory.getLog(this.getClass());
	private static final String MODEL = "/order/orderPay";
	@Autowired
	private PayService payService;
	@Autowired
	protected OrderConfig orderConfig;

	@Autowired
	private OrderService orderService;

	@Autowired
	private HttpRequestLocal httpRequestLocal;

	protected String aliPayReturnUrl;
	protected String upacppcReturnUrl;
	protected String weixinReturnUrl;
	protected String umfalipayReturnUrl;
	protected String umfweixinpayReturnUrl;
	protected String umfupacppayReturnUrl;

	@PostConstruct
	public void init() {
		this.aliPayReturnUrl = StringUtils.isBlank(orderConfig.getAliPayReturnUrl()) ? null
				: orderConfig.getAliPayReturnUrl();
		this.upacppcReturnUrl = StringUtils.isBlank(orderConfig.getUpacppcReturnUrl()) ? null
				: orderConfig.getUpacppcReturnUrl();
		this.weixinReturnUrl = StringUtils.isBlank(orderConfig.getWeixinReturnUrl()) ? null
				: orderConfig.getWeixinReturnUrl();
		this.umfalipayReturnUrl = StringUtils.isBlank(orderConfig.getUmfalipayReturnUrl()) ? null
				: orderConfig.getUmfalipayReturnUrl();
		this.umfweixinpayReturnUrl = StringUtils.isBlank(orderConfig.getUmfweixinpayReturnUrl()) ? null
				: orderConfig.getUmfweixinpayReturnUrl();
		this.umfupacppayReturnUrl = StringUtils.isBlank(orderConfig.getUmfupacppayReturnUrl()) ? null
				: orderConfig.getUmfupacppayReturnUrl();
	}

	/**
	 * 进入支付页
	 *
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@GetMapping(MODEL + "/goOrderPay.do")
	public ModelAndView goOrderPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String orderId = request.getParameter("orderId");
		Long userId = (Long) httpRequestLocal.getSessionValue("userId");
		OrderPayInfoResultDto orderPayInfoResultDto = payService.getOrderPayInfo(AppType.pc ,userId,orderId).getData();
		String paystatus = orderPayInfoResultDto.getPayStatus();
		if ("1".equals(paystatus)) {// 已支付，跳到订单详情页
			ModelAndView orderView = new ModelAndView("/order/orderList/indexDetail.html");
			orderView.addObject("orderId", orderId);
			return orderView;
		}
		PayChannelType payChannel = orderPayInfoResultDto.getPayChannel();
		ModelAndView view;
		if (payChannel == PayChannelType.primordial) {// 第三方支付
			view = new ModelAndView("/order/orderPay/payment.html");
		} else {// 联动支付
			view = new ModelAndView("/order/orderPay/umfPayment.html");
		}
		view.addObject("orderId", orderId);
		return view;
	}

	/**
	 * 订单支付
	 *
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@GetMapping(MODEL + "/orderPay.do")
	public ModelAndView orderPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PayParamDto payParamDto = new PayParamDto();
		String depositPwd = request.getParameter("depositPwd");
		if (StringUtils.isNotBlank(depositPwd)) {
			payParamDto.setDepositPwd(depositPwd);
		}
		String payType = request.getParameter("payType");
		String orderId = request.getParameter("orderId");
		String returnUrl = null;
		payParamDto.setPayType(PayType.valueOf(payType));
		if (payParamDto.getPayType() != null) {
			switch (payParamDto.getPayType()) {
			case alipay:
				returnUrl = this.aliPayReturnUrl + "?orderId=" + orderId;
				break;
			case upacppc:
				returnUrl = this.upacppcReturnUrl + "?orderId=" + orderId;
				break;
			case umfalipay:
				returnUrl = this.umfalipayReturnUrl + "?orderId=" + orderId;
				break;
			case umfweixinpay:
				returnUrl = this.umfweixinpayReturnUrl + "?orderId=" + orderId;
				break;
			case umfupacppay:
				returnUrl = this.umfupacppayReturnUrl + "?orderId=" + orderId;
				break;
			case deposit:
				break;
			case scholarship:
				break;
			default:
				throw new OrderException(ResultCode.PARAM_ERROR);
			}
		}
		payParamDto.setReturnUrl(returnUrl);
		payParamDto.setOrderId(orderId);
		OrderResult<?> result = null;
//		String ip = IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());
		try {
			Long userId = (Long) httpRequestLocal.getSessionValue("userId");
			result = payService.getOrderPay(null,AppType.pc ,userId,payParamDto);
		} catch (OrderException oe) {
			System.out.println(oe.getResultCode().getMessage());
			ModelAndView view = new ModelAndView("/error/error.html");
			view.addObject("errorMessage", oe.getResultCode().getMessage());
			return view;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		if (payParamDto.getPayType() != null) {
			Map<String, Object> map;
			switch (payParamDto.getPayType()) {
			case alipay:
			case upacppc:
				map = (Map<String, Object>) result.getData();
				String form = (String) map.get("payUrl");
				response.reset();
				response.setHeader("Content-Type", "application/x-json; charset=UTF-8");
				response.setCharacterEncoding("utf-8"); // 解决Json数据传递中文乱码
				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println(form);
				out.flush();
				out.close();
				break;
			case umfalipay:
			case umfweixinpay:
			case umfupacppay:
				map = (Map<String, Object>) result.getData();
				String payUrl = (String) map.get("payUrl");
				return new ModelAndView("redirect:" + payUrl);
			case deposit:
			case scholarship:
				ModelAndView view = new ModelAndView("/order/orderPay/paymentSuccess.html");
				view.addObject("orderId", orderId);
				return view;
			default:
				throw new OrderException(ResultCode.PARAM_ERROR);
			}
		}
		return null;
	}

	/**
	 * 订单奖励金支付
	 *
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@PostMapping(MODEL + "/orderScholarshipPay.json")
	@ResponseBody
	public JsonResult<?> orderScholarshipPay(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		PayParamDto payParamDto = new PayParamDto();
		// String payType = request.getParameter("payType");
		String orderId = request.getParameter("orderId");
		String depositPwd = request.getParameter("payPassword");
		if (StringUtils.isNotBlank(depositPwd)) {
			payParamDto.setDepositPwd(depositPwd);
		}
		payParamDto.setPayType(PayType.scholarship);
		payParamDto.setOrderId(orderId);
		Long userId = (Long) httpRequestLocal.getSessionValue("userId");
//		String ip = IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());
		OrderResult<?> result = payService.getOrderPay(null,AppType.pc ,userId,payParamDto);
		return JsonResult.success();
	}

	/**
	 * 订单微信支付
	 *
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@PostMapping(MODEL + "/orderWXPay.json")
	@ResponseBody
	public JsonResult<String> orderWXPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PayParamDto payParamDto = new PayParamDto();
		String payType = request.getParameter("payType");
		String orderId = request.getParameter("orderId");
		String returnUrl = this.weixinReturnUrl + "?orderId=" + orderId;
		payParamDto.setPayType(PayType.valueOf(payType));
		payParamDto.setReturnUrl(returnUrl);
		payParamDto.setOrderId(orderId);
		Long userId = (Long) httpRequestLocal.getSessionValue("userId");
//		String ip = IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());
		OrderResult<?> result = payService.getOrderPay(null,AppType.pc ,userId,payParamDto);
		Map<String, Object> map = (Map<String, Object>) result.getData();
		String code_url = (String) map.get("payUrl");
		return JsonResult.success(code_url);
	}

	/**
	 * 微信支付
	 *
	 * @return
	 * @throws Exception
	 */
	@GetMapping(MODEL + "/weixinPay.do")
	@ResponseBody
	public ModelAndView weixinPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code_url = request.getParameter("code_url");
		String orderId = request.getParameter("orderId");
		String surplusPayed = request.getParameter("surplusPayed");
		String returnUrl = this.weixinReturnUrl + "?orderId=" + orderId;
		ModelAndView view = new ModelAndView("/order/orderPay/weixinPay.html");
		view.addObject("code_url", code_url);
		view.addObject("orderId", orderId);
		view.addObject("surplusPayed", surplusPayed);
		view.addObject("returnUrl", returnUrl);
		return view;
	}

	/**
	 * 支付完成post同步回调地址
	 *
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@PostMapping(MODEL + "/postOrderPaySucess")
	public ModelAndView postOrderPaySucess(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String orderId = request.getParameter("orderId");
		ModelAndView view = new ModelAndView("/order/orderPay/paymentSuccess.html");
		view.addObject("orderId", orderId);
		return view;
	}

	/**
	 * 支付完成get同步回调地址
	 *
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@GetMapping(MODEL + "/getOrderPaySucess")
	public ModelAndView getOrderPaySucess(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String orderId = request.getParameter("orderId");
		ModelAndView view = new ModelAndView("/order/orderPay/paymentSuccess.html");
		view.addObject("orderId", orderId);
		return view;
	}

	/**
	 * 查看是否属于第三方店铺或者报价商品
	 *
	 * @param
	 * @return
	 */
	@PostMapping(MODEL + "/otherMerchantsByOrderId.json")
	@ResponseBody
	public JsonResult<Boolean> otherMerchantsByOrderId(HttpServletRequest request, HttpServletResponse response) {
		String parentOrderId = request.getParameter("parentOrderId");
		// 第三方店鋪不能使用预存款
		Boolean merCountFlag = OrderInfoDao.instance.countOtherMerchantsByOrderId(parentOrderId);
		// 报价商品不能使用预存款
		Boolean quoteOrderCountFlag = OrderInfoDao.instance.countQuoteOrder(parentOrderId);
		return JsonResult.success(merCountFlag || quoteOrderCountFlag);

	}

	/**
	 * 查看是否存在不能使用奖励金支付的商品或者第三方店铺商品
	 *
	 * @param
	 * @return
	 */
	@PostMapping(MODEL + "/cannotByScholarship.json")
	@ResponseBody
	public JsonResult<Boolean> cannotByScholarship(HttpServletRequest request, HttpServletResponse response) {
		String parentOrderId = request.getParameter("parentOrderId");
		// 不能使用奖励金支付的商品
		// Boolean flag = ErpOrderInfoDao.instance.cannotByScholarship(parentOrderId);
		// 第三方店鋪不能使用奖励金
		Boolean merCountFlag = OrderInfoDao.instance.countOtherMerchantsByOrderId(parentOrderId);
		return JsonResult.success(merCountFlag);

	}

	/**
	 * 支付成功页面
	 *
	 * @param
	 * @return
	 */
	@PostMapping(MODEL + "/getPayOrderInfo.json")
	@ResponseBody
	public JsonResult<PayOrderResultDto> getPayOrderInfo(HttpServletRequest request, HttpServletResponse response) {
		String orderId = request.getParameter("orderId");
		Long userId = (Long) httpRequestLocal.getSessionValue("userId");
		PayOrderResultDto payOrderResultDto = orderService.getPayAfterOrderInfo(userId,orderId).getData();
		return JsonResult.success(payOrderResultDto);
	}

}
